use strict;
use warnings;
use Test::More;
use Time::Fake;
use Cammy::Fetch::Weather;
use DateTime;

BEGIN { unlink 'Halifax.weather' }
END { unlink 'Halifax.weather' }

my $conf = {
    location_name   => 'Halifax',
    latitude        => '44.87N',
    longitude       => '64.12W',
    weather_url     => q{http://dd.weatheroffice.gc.ca/citypage_weather/xml/NS/s0000318_e.xml},
};

my $weather = report_weather($conf);
ok $weather;
isa_ok $weather, 'HASH';

for my $i (1..11) {
    my $offset = sprintf( '+%dm', $i * 5);
    note "$i: $offset";
    Time::Fake->offset($offset);
    my $new_weather = report_weather($conf);
    is_deeply $new_weather, $weather;
}
for my $i (12..15) {
    my $offset = sprintf( '+%dm', $i * 5);
    note "$i: $offset";
    Time::Fake->offset($offset);
    my $new_weather = report_weather($conf);
    isnt $new_weather->{weather}, $weather->{weather};
}

my $new_weather = report_weather($conf);

my $time_regex = qr/\b(?<hour>\d?\d):(?<minute>\d\d)(?<ampm>[AP]M)\b/i;
my $year = DateTime->now->year;

my $new_time;
if ( $new_weather->{weather} =~ /$time_regex/ ) {
    my $hour = ( $+{ampm} =~ /am/i ? $+{hour} : $+{hour}+12 );
    $hour = 12 if $hour == 24; # noon is 12pm
    $new_time = DateTime->new(
        time_zone   => 'local',
        hour        => $hour,
        minute      => $+{minute},
        year        => $year,
    );
    note "$new_weather->{weather} -> $new_time";
}

my $old_time;
if ( $weather->{weather} =~ /$time_regex/ ) {
    my $hour = ( $+{ampm} =~ /am/i ? $+{hour} : $+{hour}+12 );
    $hour = 12 if $hour == 24; # noon is 12pm
    $old_time = DateTime->new(
        time_zone   => 'local',
        hour        => $hour,
        minute      => $+{minute},
        year        => $year,
    );
    note "$weather->{weather} -> $old_time";
}
isa_ok $new_time, 'DateTime';
isa_ok $old_time, 'DateTime';

cmp_ok $new_time, '>', $old_time
    or diag explain {
        new => { time => "$new_time", weather => $new_weather },
        old => { time => "$old_time", weather => $weather }
    };

done_testing;
